/*
 * @Author: MrDotYan 2564217790@qq.com
 * @Date: 2024-09-10 22:39:53
 * @LastEditors: MrDotYan 2564217790@qq.com
 * @LastEditTime: 2024-09-13 22:47:06
 * @FilePath: /webServer/src/guard/role.guard.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Guard, IGuard, getPropertyMetadata } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { ROLE_META_KEY } from '../decorator/role.decorator';
import { isNotEmpty } from '../utils/isHelper';
import { UserService } from '../service/user/user.service';

@Guard()
export class AuthGuard implements IGuard<Context> {
  async canActivate(
    context: Context,
    supplierClz,
    methodName: string
  ): Promise<boolean> {
    // 从类元数据上获取角色信息
    const roleNameList = getPropertyMetadata<string[]>(
      ROLE_META_KEY,
      supplierClz,
      methodName
    );
    const { uid } = context.header;
    if (roleNameList && roleNameList.length && uid) {
      const userService = await context.requestContext.getAsync(UserService);
      const user = await userService.info(uid);
      const { role } = user;
      if (!isNotEmpty(role)) {
        return false;
      }
      const roles = role.map(ele => ele.roleCode);
      return roles.every(ele => roleNameList.includes(ele));
    }

    return true;
  }
}
